package corej.exam.com.usermgmt;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class UserServer {

    public static void main(String[] args) throws Exception {
        ServerSocket ss = null;
        try {
            ss = new ServerSocket(9000);
        } catch (IOException e) {
            e.printStackTrace();
        }
        while (true) {
            ss.accept();
            System.out.println("ServerSocket ss has returned accept()");
            Socket s = ss.accept();
            Thread t = new ServerThread(s);
            t.start();
        }

    }

}

class ServerThread extends Thread {
    private Socket s;

    public ServerThread(Socket s) {
        super();
        this.s = s;
    }

    public void run() {
        try {
            InputStream is = s.getInputStream();
            ObjectInputStream in = new ObjectInputStream(is);
            Object obj = null;
            try {
                obj = in.readObject();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            while (true) {
                Set set = (HashSet) obj;
                print(set);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                s.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public static void print(Collection c) {
        Iterator it = c.iterator();
        while (it.hasNext()) {
            User u = (User) it.next();
            System.out.println(u);
        }
    }
}